package sreal.study;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGProxyFactory implements MethodInterceptor{
    private Object target;

    public static Object getInstance(Object target){
        CGProxyFactory proxy=new CGProxyFactory(target);
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(proxy.target.getClass());
        enhancer.setCallback(proxy);
        return enhancer.create();
    }

    public CGProxyFactory(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        long startTime =System.currentTimeMillis();
        methodProxy.invokeSuper(o,objects);
        long endTime= System.currentTimeMillis();
        System.out.println(objects[0]+" : costs "+(endTime-startTime)+"ms");
        return null;
    }
}
